package com.zh.webcommon.common.param.constraint;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Arrays;


public class ValueOptionValidate implements ConstraintValidator<ValueOptions, Object> {
    private ValueOptions logo;

    @Override
    public void initialize(ValueOptions logo) {
        this.logo = logo;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 处理空值：null或空字符串视为有效（需文档说明）
        if (value == null || ((value instanceof String str) && str.isEmpty())) {
            return true;
        }

        if (logo.options().length == 0 && logo.optionsRef() != Enum.class) {
            var enumValues = logo.optionsRef().getEnumConstants();
            return Arrays.stream(enumValues).map(Enum::name).anyMatch(e -> e.equals(value.toString()));
        }

        return Arrays.asList(logo.options()).contains(value.toString());
    }
}